import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'BaseViewModel.dart';
import 'package:provider/provider.dart';

/*View基类*/
class BaseView<T extends BaseViewModel> extends StatefulWidget {
  final Widget Function(BuildContext context, T viewModel, Widget? child) build;
  final T viewModel;
  final Widget? child;
  final Function(T) onModelReady;

  const BaseView(
      {super.key,
      required this.viewModel,
      required this.build,
      this.child,
      required this.onModelReady});

  @override
  State<BaseView<T>> createState() => _StatefulWidgetState<T>();

  //MARK: - method
  // loading加载视图
  static Widget loadingWidget() {
    return Container(
        margin: EdgeInsets.zero,
        color: Colors.transparent,
        alignment: Alignment.center,
        child: const SizedBox(
          width: 30,
          height: 30,
          child: CircularProgressIndicator(
            backgroundColor: Colors.transparent,
            color: Colors.deepPurple,
            strokeWidth: 2,
          ),
        ));
  }
}

class _StatefulWidgetState<T extends BaseViewModel> extends State<BaseView<T>>
    with AutomaticKeepAliveClientMixin {
  late T viewModel;

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true; //tabBar切换保持原状态(防止重复请求加载)

  @override
  void initState() {
    viewModel = widget.viewModel;
    widget.onModelReady(viewModel);

    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);

    // TODO: implement build
    return ChangeNotifierProvider<T>(
      child: Consumer<T>(
        builder: widget.build,
        child: widget.child,
      ),
      create: (BuildContext context) {
        return viewModel;
      },
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    debugPrint('$runtimeType 已销毁');
  }
}
